<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreRoleRequest;
use App\Http\Requests\UpdateRoleRequest;
use App\Http\Resources\RoleResource;
use App\Http\Traits\CheckPermission;
use App\Http\Traits\LogOperation;
use App\Models\Permission;
use App\Models\Role;
use App\Services\RoleService;
use Illuminate\Http\Request;

class RoleController extends Controller
{
    use CheckPermission, LogOperation;

    protected $roleService;
    protected $resource = 'roles';

    public function __construct(RoleService $roleService)
    {
        $this->roleService = $roleService;
        $this->middleware('auth.api');
    }

    public function index(Request $request)
    {
        // 检查查看权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_VIEW);

        $filters = $request->only(['name', 'status']);
        $query = $this->roleService->buildQuery($filters);
        $roles = $query->paginate($this->getPageSize($request));

        // 使用Resource格式化分页数据，包括时间字段
        $roles->setCollection(
            $roles->getCollection()->map(function ($role) {
                return (new RoleResource($role))->resolve(request());
            })
        );

        return $this->success($roles, '获取成功');
    }

    public function store(StoreRoleRequest $request)
    {
        // 检查新增权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_CREATE);

        $role = $this->roleService->create($request->validated());
        
        // 记录创建操作
        $this->logCreate($this->resource, $role, "创建角色: {$role->name}", $request);
        
        return $this->success(new RoleResource($role), '创建成功');
    }

    public function show($id)
    {
        // 检查查看权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_VIEW);

        $role = Role::with(['menus', 'permissions'])->findOrFail($id);
        return $this->success(new RoleResource($role), '获取成功');
    }

    public function update(UpdateRoleRequest $request, $id)
    {
        // 检查编辑权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_UPDATE);
        
        $role = Role::findOrFail($id);
        // 保存更新前的数据
        $originalData = $role->toArray();
        
        $role = $this->roleService->update($role, $request->validated());

        // 更新角色权限
        if ($request->has('permission_ids')) {
            $role->permissions()->sync($request->permission_ids);
        }

        // 更新角色菜单
        if ($request->has('menu_ids')) {
            $role->menus()->sync($request->menu_ids);
        }

        // 记录更新操作
        $this->logUpdate($this->resource, $role, $originalData, "更新角色: {$role->name}", $request);

        // 清除所有用户权限缓存
        $permissionService = app(\App\Services\PermissionService::class);
        $permissionService->clearAllPermissionCache();

        return $this->success(new RoleResource($role), '更新成功');
    }

    public function destroy($id)
    {
        // 检查删除权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_DELETE);

        $role = Role::findOrFail($id);
        
        // 记录删除操作（在删除前记录）
        $this->logDelete($this->resource, $role, "删除角色: {$role->name}", request());
        
        $this->roleService->delete($role);
        
        // 清除权限缓存
        $permissionService = app(\App\Services\PermissionService::class);
        $permissionService->clearAllPermissionCache();
        
        return $this->success(null, '删除成功');
    }

    public function all()
    {
        $roles = Role::enabled()
            ->orderBy('sort')
            ->get();

        return $this->success($roles, '获取成功');
    }
}

